from tkinter import *
import time
from tkinter import messagebox


class StopWatch(Frame):
    msec = 50

    def __init__(self, parent=None, **kw):
        super().__init__(parent, kw)
        self._start = 0.0
        self._elapsed_time = 0.0
        self._running = False
        self.timestr = StringVar()
        self.history = []  # List to store history of times
        self.create_widgets()

    def create_widgets(self):
        l = Label(self, textvariable=self.timestr, justify=LEFT)
        self.set_time(self._elapsed_time)
        l.pack(fill=X, expand=YES, pady=2, padx=2)

        self.start_button = Button(self, text='开始', command=self.start)
        self.start_button.pack(side=LEFT)

        self.stop_button = Button(self, text='停止', command=self.stop)
        self.stop_button.pack(side=LEFT)

        self.reset_button = Button(self, text='重置', command=self.reset)
        self.reset_button.pack(side=LEFT)

        self.history_button = Button(self, text='历史记录', command=self.show_history)
        self.history_button.pack(side=LEFT)

        self.exit_button = Button(self, text='退出', command=self.quit)
        self.exit_button.pack(side=LEFT)

    def _update(self):
        self._elapsed_time = time.time() - self._start
        self.set_time(self._elapsed_time)
        self._timer = self.after(self.msec, self._update)

    def set_time(self, elap):
        minutes = int(elap / 60)
        seconds = int(elap - minutes * 60.0)
        hseconds = int((elap - minutes * 60.0 - seconds) * 100)
        self.timestr.set(f'{minutes:02d}:{seconds:02d}:{hseconds:02d}')

    def start(self):
        if not self._running:
            self._start = time.time() - self._elapsed_time if self._elapsed_time > 0 else time.time()
            self._update()
            self._running = True

    def stop(self):
        if self._running:
            self.after_cancel(self._timer)
            self._running = False
            self.record_time()  # Record the current time when stopped

    def reset(self):
        self._start = time.time()
        self._elapsed_time = 0.0
        self.set_time(self._elapsed_time)
        self._running = False

    def record_time(self):
        # Record the current elapsed time to history
        self.history.append(self._elapsed_time)
        print("Time recorded:", self.format_time(self._elapsed_time))

    def format_time(self, seconds):
        minutes = int(seconds / 60)
        seconds = int(seconds - minutes * 60)
        minsec = seconds-minutes
        return f'{minutes:02d}:{seconds:02d}'

    def show_history(self):
        history_str = '\n'.join([self.format_time(time) for time in self.history])
        messagebox.showinfo("历史记录", history_str)


if __name__ == '__main__':
    root = Tk()
    root.title('秒表计时器')
    root.geometry('300x100')

    sw = StopWatch(root)
    sw.pack(side=TOP)
    root.mainloop()
